<template>
    <el-form :model="form" ref="formRef" label-width="100px" style="margin-top: 20px;">
        <el-row>
            <el-col :span="6">
                <el-form-item label="客户姓名">
                    <el-input v-model="form.name" placeholder="请输入客户姓名"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="客户手机">
                    <el-input v-model="form.phone" placeholder="请输入客户手机"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="归属人">
                    <el-input v-model="form.owner" placeholder="请输入商机归属人"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="10">
                <el-form-item label="跟进时间">
                    <el-date-picker v-model="form.followTime" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-button type="primary" style="margin-left: 20px;" @click="handleSearch">
                    <el-icon>
                        <Search />
                    </el-icon>
                    搜索
                </el-button>
                <el-button style="margin-left: 20px;" @click="handleReset">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    重置
                </el-button>
            </el-col>
        </el-row>
    </el-form>
    <el-row style="margin-left: 20px;margin-top: 20px;">
        <el-col :span="22">
            <el-button type="primary" plain :icon="Plus" @click="open">新增</el-button>
            <el-button type="success" :icon="Edit" @click="editSelected" >修改</el-button>
            <el-button type="danger" plain :icon="Delete" @click="removeSelected">删除</el-button>
        </el-col>
        <el-col :span="2" style="text-align: right;">
            <el-tooltip content="隐藏搜索" placement="top">
                <el-button :icon="Search" circle @click="toggleSearch"></el-button>
            </el-tooltip>
            <el-tooltip content="刷新" placement="top">
                <el-button :icon="Refresh" circle @click="refreshData"></el-button>
            </el-tooltip>
        </el-col>
    </el-row>
    <el-table :data="tableData" style="margin-top: 20px;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column property="name" label="客户姓名" width="140" />
        <el-table-column property="phone" label="手机号码" width="140" show-overflow-tooltip />
        <el-table-column property="owner" label="商机归属" width="140" />
        <el-table-column property="createTime" label="创建时间" width="180" />
        <el-table-column property="status" label="商机状态" width="120">
            <template #default="scope">
                <el-tag type="primary" v-if="scope.row.status === 1">已分配</el-tag>
                <el-tag type="info" v-else>未分配</el-tag>
            </template>
        </el-table-column>
        <el-table-column property="nextTime" label="下次跟进时间" width="180" />
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="text" size="small" @click="edit(scope.row)">
                    <el-icon>
                        <Edit />
                    </el-icon>
                    分配
                </el-button>
                <el-button type="text" size="small" v-if="scope.row.owner === 'admin01'" @click="followUp(scope.row)">
                    <el-icon>
                        <Pointer />
                    </el-icon>
                    跟进
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <div class="page" style="margin-top: 20px; display: flex; justify-content: flex-end;">
        <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>
    <el-dialog v-model="centerDialogVisible" :title="title" width="800px" align-center>
        <el-form :model="editForm" ref="dialogFormRef">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="手机号码">
                        <el-input v-model="editForm.phone" placeholder="请输入手机号码" style="width: 250px;"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="客户姓名">
                        <el-input v-model="editForm.name" placeholder="请输入客户姓名" style="width: 250px;"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="渠道来源">
                        <el-select v-model="editForm.source" placeholder="请选择渠道来源" style="width: 240px"
                            @visible-change="sourcechange">
                            <el-option v-for="item in options" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="活动信息">
                        <el-select v-model="editForm.activity" placeholder="请选择活动信息" style="width: 250px;"
                            @visible-change="handleActivityChange">
                            <el-option v-for="item in optionactive" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    客户性别:
                    <el-radio-group v-model="editForm.gender">
                        <el-radio :label="0">男</el-radio>
                        <el-radio :label="1">女</el-radio>
                        <el-radio :label="2">未知</el-radio>
                    </el-radio-group>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="客户年龄">
                        <el-input-number v-model="editForm.age" placeholder="请输入客户年龄" :min="0"></el-input-number>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="微信号">
                        <el-input v-model="editForm.weixin" placeholder="请输入微信号" style="width: 265px;"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="QQ号">
                        <el-input v-model="editForm.qq" placeholder="请输入QQ号" style="width: 270px;"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="add" type="primary">确定</el-button>
                <el-button @click="centerDialogVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="followUpDialogVisible" title="分配商机" width="800px" align-center>
        <el-form :model="followUpForm" ref="followUpFormRef">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="所属部门">
                        <el-tree-select v-model="followUpForm.departmentId" :data="departments" check-strictly
                            :render-after-expand="false" style="width: 220px" @visible-change="bumnelist"
                            placeholder="审批部门" />
                    </el-form-item>

                </el-col>
                <el-col :span="12">
                    <el-form-item label="分配给">
                        <el-select v-model="followUpForm.approverId" placeholder="选择用户" clearable style="width: 220px"
                            @visible-change="prlist">
                            <el-option v-for="item in approvers" :key="item.userId" :label="item.nickName"
                                :value="item.userId" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="fenpei" type="primary">确定</el-button>
                <el-button @click="centerDialogVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { getBusinessList, addBusiness, channelslist, fromTemplate, updateBusiness, deleteBusiness, assignment } from '@/api/buiness/index'
import { ref } from 'vue'
import { Search, Refresh, Plus, Edit, Delete, Pointer } from '@element-plus/icons-vue'

const options = ref<any[]>([])
const approvers = ref<any[]>([])
const departments = ref<any[]>([])
const title = ref('')
const centerDialogVisible = ref(false)
const followUpDialogVisible = ref(false)
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const selectedRows = ref<any[]>([])
const editForm = ref({
    id: '',
    name: '',
    phone: '',
    owner: '',
    followTime: '',
    source: '',
    activity: '',
    gender: 2,
    age: null,
    weixin: '',
    qq: ''
})
const form = ref({
    name: '',
    phone: '',
    owner: '',
    followTime: ''
})

const followUpForm = ref({
    departmentId: '',
    approverId: ''
})

const tableData = ref<any[]>([])
const total = ref(0)
const optionactive = ref([])

const handleSelectionChange = (rows: any[]) => {
    selectedRows.value = rows
}

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    pageSize4.value = val
    getList()
}

const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    currentPage4.value = val
    getList()
}

const handleSearch = () => {
    console.log('搜索')
    currentPage4.value = 1
    getList()
}

const handleReset = () => {
    form.value = {
        name: '',
        phone: '',
        owner: '',
        followTime: ''
    }
    currentPage4.value = 1
    pageSize4.value = 10
    getList()
}

const open = () => {
    console.log('新增')
    centerDialogVisible.value = true
    title.value = '添加商机'
    editForm.value = {
        id: '',
        name: '',
        phone: '',
        owner: '',
        followTime: '',
        source: '',
        activity: '',
        gender: 2,
        age: null,
        weixin: '',
        qq: ''
    }
   
   
}
const fenpeifrom: any = {}
const edit = (row: any) => {
    fenpeifrom.businessId = row.businessId
    fenpeifrom.name = row.name
    fenpeifrom.phone = row.phone
    fenpeifrom.owner = row.owner
    fenpeifrom.followTime = row.followTime
    fenpeifrom.source = row.source
    fenpeifrom.activity = row.activity
    fenpeifrom.gender = row.gender
    fenpeifrom.age = row.age
    fenpeifrom.weixin = row.weixin
    fenpeifrom.qq = row.qq
    console.log(fenpeifrom)
    console.log('修改:', row)
    followUpDialogVisible.value = true
}

const editSelected = () => {
    
    console.log('修改选中行')
    if (selectedRows.value.length === 1) {
        centerDialogVisible.value = true
        title.value = '修改商机'
        editForm.value = {
            id: selectedRows.value[0].businessId,
            name: selectedRows.value[0].name,
            phone: selectedRows.value[0].phone,
            owner: selectedRows.value[0].owner,
            followTime: selectedRows.value[0].followTime,
            source: selectedRows.value[0].source,
            activity: selectedRows.value[0].activity,
            gender: selectedRows.value[0].gender,
            age: selectedRows.value[0].age,
            weixin: selectedRows.value[0].weixin,
            qq: selectedRows.value[0].qq
        }
    } else {
        //禁用

    }
}

const remove = (row: any) => {
    console.log('删除:', row)
    // 这里可以添加删除逻辑
}

const removeSelected = () => {
    console.log('删除选中行')
    // 这里可以添加删除逻辑
    if (selectedRows.value.length >= 1) {
        const businessIds = selectedRows.value.map((item: any) => item.businessId)
        console.log(businessIds)
        deleteBusiness({ businessIds: businessIds.join(',') }).then((res) => {
            console.log(res)
            getList() // 刷新列表以显示删除的行
        }).catch((error) => {
            console.error('删除商机失败', error)
        })
    }
}

const refreshData = () => {
    console.log('刷新数据')
    getList()
}

const toggleSearch = () => {
    console.log('隐藏/显示搜索')
    // 实现隐藏/显示搜索逻辑
}

const getList = () => {
    const params = {
        pageNum: currentPage4.value,
        pageSize: pageSize4.value,
        name: form.value.name,
        phone: form.value.phone,
        owner: form.value.owner,
        followTime: form.value.followTime
    }

    getBusinessList(params).then((res) => {
        console.log(res)
        tableData.value = res.rows
        total.value = res.total
    }).catch((error) => {
        console.error('获取商机列表失败', error)
    })
}

const add = () => {
    if (title.value === '添加商机') {
        console.log(editForm.value)
        addBusiness(editForm.value).then((res) => {
            console.log(res)
            centerDialogVisible.value = false
            getList() // 刷新列表以显示新增商机
        }).catch((error) => {
            console.error('新增商机失败', error)
        })
    } else {
        updateBusiness(editForm.value).then((res) => {
            console.log(res)
            centerDialogVisible.value = false
            getList() // 刷新列表以显示修改商机
        }).catch((error) => {
            console.error('修改商机失败', error)
        })
    }
}



const followUp = (row: any) => {
    console.log('跟进:', row)

    router.push({ path: `/business/details/index/${row.businessId}/follow`, query: { id: row.businessId } });


    // 这里可以添加跟进逻辑
}

const sourcechange = (val: boolean) => {
    if (val && options.value.length === 0) { // 只有当下拉框展开且选项为空时才获取数据
        console.log('渠道来源:', val)
        channelslist({}).then((res) => {
            console.log(res)
            options.value = res.data.map((item: any) => ({
                label: item.channelName,
                value: item.channelId
            }))
        }).catch((error) => {
            console.error('获取渠道来源失败', error)
        })
    }
}

const handleActivityChange = (val: number) => {
    console.log('活动信息:', val)
    // 这里可以添加活动信息变化的逻辑
    if (options.value.length > 0) {
        fromTemplate({ channelId: options.value[0].value }).then((res) => {
            console.log(res)
            optionactive.value = res.data.map((item: any) => ({
                label: item.name,
                value: item.channelId
            }))
        }).catch((error) => {
            console.error('获取活动信息失败', error)
        })
    }
    console.log(optionactive.value)
}
import { userlist, personlist, } from '@/api/contract/index'
import router from '@/router'

const bumnelist = (val: boolean) => {
    userlist({}).then((res) => {
        departments.value = res.data.map((item: any) => {
            return {
                label: item.label,
                value: item.id,
                children: item.children?.map((child: any) => {
                    return {
                        label: child.label,
                        value: child.id,
                        children: child.children?.map((grandson: any) => {
                            return {
                                label: grandson.label,
                                value: grandson.id
                            }
                        })
                    }
                })
            }
        })
        console.log(departments.value.value, 'data')
    }).catch((error) => {
        console.error('获取用户列表失败', error)
    })
}

const prlist = (val: boolean) => {
    personlist({ deptId: followUpForm.value.departmentId }).then((res) => {
        approvers.value = res.data as { userId: number, nickName: string }[]
        console.log(approvers.value)
    }).catch((error) => {
        console.error('获取审批人列表失败', error)
    })
}

getList()
function fenpei() {

    assignment({
        assignId :1371,
        departmentId: 100,
        deptId: 103,
        nickName: followUpForm.value.approverId,
        type:1,
        userId:1,
        userName:"admin"

    }).then((res) => {
        console.log(res)
        followUpDialogVisible.value = false
        getList() // 刷新列表以显示分配的商机
    }).catch((error) => {
        console.error('分配商机失败', error)
    })
}
</script>

<style scoped lang="scss">
.el-popper.is-customized {
    padding: 6px 12px;
    background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
    background: linear-gradient(45deg, #b2e68d, #bce689);
    right: 0;
}

.el-form-item {
    margin-bottom: 10px;
}

.el-date-picker {
    width: 100%;
}

.el-button {
    margin-right: 10px;
}

.page {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    margin-right: 20px; // 修正拼写错误
}
</style>
